package com.example.petstore.service.std;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eudi.ssm.petstore.web.model.PagingList;
import com.example.petstore.persist.model.Product;
import com.example.petstore.persist.model.ProductMapper;
import com.example.petstore.service.ProductService;

@Service
public class ProductServiceStdImpl implements ProductService {

	@Autowired
	private ProductMapper productMapper;
	
	@Override
	public void addProduct(Product product) {
		this.productMapper.addProduct(product);
	}

	@Override
	public void deleteProduct(int id) {
		this.productMapper.deleteProduct(id);
	}

	@Override
	public void updateProduct(Product product) {
		this.productMapper.updateProduct(product);
	}

	@Override
	public Product selectById(int id) {
		return this.productMapper.selectById(id);
	}

	@Override
	public PagingList<Product> findProducts(int id, String name,
			float fromPrice, float toPrice, int pageIndex, int pageSize) {
		int total = this.productMapper.matches(id, name, fromPrice, toPrice);
		int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
		if(pageIndex > pageCount)
			pageIndex = pageCount;
		int fetchIndex = (pageIndex - 1) * pageSize;
		int fetchCount = fetchIndex + pageSize > total ? (total - fetchIndex) : pageSize;
		List<Product> list = this.productMapper.findProducts(id, name, fromPrice, toPrice, fetchIndex, fetchCount);
		PagingList<Product> paging = new PagingList<Product>();
		paging.setItemCount(total);
		paging.setPageCount(pageCount);
		paging.setPageIndex(pageIndex);
		paging.setPageSize(pageSize);
		paging.setItems(list);
		return paging;
	}

}
